package com.sf.trtms.trade.personal.utils;
import java.io.UnsupportedEncodingException;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

import com.sf.trtms.trade.personal.exceptions.TbpRuntimeException;

public class MySqlCrypto {
	/**
	 * AES-密钥
	 * @param key--密钥串
	 * @param encoding--编码
	 * @return
	 */
	private static SecretKeySpec generateMySQLAESKey(final String key,
			final String encoding) {
		try {
			final byte[] finalKey = new byte[16];
			int i = 0;
			for (byte b : key.getBytes(encoding))
				finalKey[i++ % 16] ^= b;
			return new SecretKeySpec(finalKey, "AES");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 字符串AES加密(mysql)
	 * @param src-- 需要加密的字符串
	 * @param key-- 密钥
	 * @return
	 */
	public static String mysqlEncryptToHex(String src, String key) {
		String encryptString = null;
		try {
			Cipher encryptCipher = Cipher.getInstance("AES");
			SecretKeySpec secretKeySpec = generateMySQLAESKey(key, "UTF-8");// 密钥
			encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

			byte[] bytes = encryptCipher.doFinal(src.getBytes());
			encryptString = new String(Hex.encodeHex(bytes));
		} catch (Throwable t) {
			throw new TbpRuntimeException("The MySqlCrypto.mysqlEncryptToHex Exception!");
		}
		return encryptString;
	}

	/**
	 * 字符串AES解密(mysql)
	 * @param value--加密后的十六进制字符串
	 * @param key-- 密钥
	 * @return
	 */
	public static String mysqlDecryptToHex(String value, String key) {
		String decryptString = null;
		try {
			Cipher decryptCipher = Cipher.getInstance("AES");
			SecretKeySpec secretKeySpec = generateMySQLAESKey(key, "UTF-8");// 密钥
			decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

			byte[] bytes = Hex.decodeHex(value.toCharArray());
			bytes = decryptCipher.doFinal(bytes);
			decryptString = new String(bytes);
		} catch (Throwable t) {
			throw new TbpRuntimeException("The MySqlCrypto.mysqlDecryptToHex Exception!");
		}
		return decryptString;
	}
}
